package com.wbao.dianniu.ui;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.KnowListAdapter;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleActionListener;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.KnowledgeData;
import com.wbao.dianniu.listener.IKnowledgeListListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.KnowListManager;
import com.wbao.dianniu.update.KnowledgeHelper;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 电商干货
 * <p>
 * Created by Administrator on 2017/8/30.
 */

public class KnowListActivity extends Activity implements IKnowledgeListListener, View.OnClickListener, KnowledgeHelper.IKnowledgeChangedListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    //    private EditText myEditText;
//    private ImageView searchIV;
    private PullToRefreshListView pullListView;
    private ListView listView;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private KnowListManager manager;
    //    private String searchKey = null;
    private KnowListAdapter adapter;
    //    private List<KnowledgeData> mList = new ArrayList<KnowledgeData>();
    private final int TYPE = 1;
    private ImageView backBtn;
    //    private Button cancelBtn;
    private EditText clearEditText;
    private ImageView keySearchIV;
    private TextView noDataTV;
    private TextView titleTV;
    private Dialog dialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_knowledge_list);
        initTitle();
        initWattingView();
        initView();
        initData();
        requestData(currentPage);
        KnowledgeHelper.getInstance().addListener(this);
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void initTitle() {
        backBtn = (ImageButton) findViewById(R.id.back_button);
        backBtn.setOnClickListener(this);
        titleTV = findViewById(R.id.title);
        titleTV.setText(getResources().getString(R.string.knowledge_shared));
        keySearchIV = findViewById(R.id.knowledge_key_search_iv);
        clearEditText = findViewById(R.id.know_key_search_et);
        /*clearEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    toSearch();
                    return true;
                }
                return false;
            }
        });*/
        clearEditText.setOnEditorActionListener(new NoDoubleActionListener() {
            @Override
            public void noDoubleAciton() {
                toSearch();
            }
        });
        keySearchIV.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                toSearch();
            }
        });
    }

    private void showDialog() {
        dialog = LoadingWaitDialog.createLoadingDialog(this, "");
        dialog.setCancelable(false);
        dialog.show();
    }

    private void initView() {
        pullListView = findViewById(R.id.knowledge_listview);
        pullListView.setMode(Mode.PULL_UP_TO_REFRESH);
        pullListView.setOnRefreshListener(onRefreshListener);
        listView = pullListView.getRefreshableView();
        registerForContextMenu(listView);

        noDataTV = findViewById(R.id.no_data_tv);
    }

    private void initData() {
        manager = new KnowListManager(this);
        manager.addKnowledgeListListener(this);
        adapter = new KnowListAdapter(this, 1);
        adapter.addData(new ArrayList<KnowledgeData>());
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(itemClickListener);
    }

    private void toSearch() {
        showDialog();
        String content = clearEditText.getText().toString().trim();
        adapter.cleanData();
        currentPage = 0;
        requestData(currentPage);
    }

    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            KnowledgeData data = (KnowledgeData) adapter.getItem(position - 1);
            ActivityUtils.intoKnowDetailActivity(KnowListActivity.this, 0, data);
        }
    };


    PullToRefreshBase.OnRefreshListener onRefreshListener = new PullToRefreshBase.OnRefreshListener() {

        @Override
        public void onRefresh() {
            //  上拉刷新 加载请求数据
            pullUpRequest();
        }
    };

    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        requestData(currentPage);
    }

    private void requestData(int page) {
        String searchKey = clearEditText.getText().toString().trim();
        manager.knowledgeList(GlobalContext.getAccountId(), TYPE, searchKey, page * PAGE_COUNTS, PAGE_COUNTS);
    }

    @Override
    public void onKnowledgeListFailure(int errorCode, String errorMsg) {
        pullListView.onRefreshComplete(false, false);
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText(errorMsg == null ? "" : errorMsg);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onKnowledgeListSuccess(List<KnowledgeData> list) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        pullListView.onRefreshComplete(false, true);
        waittingLayout.setVisibility(View.GONE);
        if (null != list) {
            adapter.addData(list);
            if (adapter.getCount() == 0) {
                noDataTV.setVisibility(View.VISIBLE);
            } else {
                noDataTV.setVisibility(View.GONE);
                Utils.hideSoftInput(this, clearEditText);
            }
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_button:
                finish();
                break;
           /* case R.id.knowledge_key_search_iv:
                toSearch();
                break;*/
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeKnowledgeListListener(this);
        }
        KnowledgeHelper.getInstance().removeListener(this);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void addOneKnowledge(KnowledgeData data) {

    }

    @Override
    public void removeOneKnowledge(int knowledgeId) {
        adapter.removeOneData(knowledgeId);
        if (adapter.getCount() == 0) {
            noDataTV.setVisibility(View.VISIBLE);
        } else {
            noDataTV.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void goodNotify(int knowledgeId, int isGood, int goodCount) {
        adapter.goodChanged(knowledgeId, isGood, goodCount);
    }

    @Override
    public void replyNotify(int knowledgeId, int answerCounts) {
        adapter.replyNotify(knowledgeId, answerCounts);
    }

    @Override
    public void visitorNotify(int knowledgeId, int visitorCounts) {
        adapter.visitorNotify(knowledgeId, visitorCounts);
    }

    @Override
    public void modifyOneData(int knowledgeId, KnowledgeData data) {

    }
}
